
use wtask_base::{error::WResult, export::serde_to_string};
use wtask_file::{IncomingBody, Request, Response, StatusCode, header};

use crate::basic::{parse_body_string, response_body, ResponseBody, WEB_SESSION};



pub(crate) async fn response_logout(req: Request<IncomingBody>, token: &str) -> WResult<Response<ResponseBody>> {
    let machine_logout = parse_body_string(req, token).await?;
    // log_debug!("Web login data: {:?}", machine_logout);

    let json = if machine_logout == "list" {
        // list
        if let Some(machines) = WEB_SESSION.login.read().await.as_ref().get(token) {
            let data_res = machines.values().map(| v | (v.config.to_string(), &v.home, &v.config)).collect::<Vec<_>>();
            serde_to_string(&data_res)?
        } else {
            "[]".to_string()
        }
    } else if machine_logout == "all" {
        // logout all
        if let Some(machines) = WEB_SESSION.login.write().await.as_mut().get_mut(token) {
            machines.clear();
        }
        "[]".to_string()
    } else if let Some(machines) = WEB_SESSION.login.write().await.as_mut().get_mut(token) {
        // login, logout someone
        machines.remove(&machine_logout);
        let data_res = machines.values().map(| v | &v.config).collect::<Vec<_>>();
        serde_to_string(&data_res)?
    } else {
        // no login
        "[]".to_string()
    };

    let response = Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "application/json")
        .body(response_body(&json, token)).unwrap();
    Ok(response)
}
